<template>
  <Modal title="修改密码" :value="visible" width="500px" @on-cancel="onCancel" :mask-closable="false">
    <div>
      <Form ref="forms" :model="params" :rules="rules" :label-width="100">
        <FormItem prop="password" label="原密码">
          <Input type="password" v-model="params.password" placeholder="请输入原密码" style="width: 300px"></Input>
        </FormItem>
        <FormItem prop="newPassword" label="新密码">
          <Input type="password" v-model="params.newPassword" placeholder="请输入新密码" style="width: 300px"></Input>
        </FormItem>
        <FormItem prop="passwdCheck" label="确认新密码">
          <Input type="password" v-model="params.passwdCheck" placeholder="请输入新密码" style="width: 300px"></Input>
        </FormItem>
      </Form>
    </div>
    <div class="text-center" slot="footer">
      <Button type="primary" @click="onModalOK">确定</Button>
    </div>
  </Modal>
</template>

<script>
import modalMixin from "@/mixins/crud.modal.js";
import * as RULE from "@/utils/validate";
export default {
  name: "AdminModal",
  mixins: [modalMixin],
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 6) {
        callback(new Error("密码至少6位"));
      } else {
        if (this.params.passwdCheck) {
          // 对第二个密码框单独验证
          this.$refs.forms.validateField("passwdCheck");
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入新密码"));
      } else if (value !== this.params.newPassword) {
        callback(new Error("两次密码输的不一样!"));
      } else {
        callback();
      }
    };
    return {
      params: this.initData(),
      rules: {
        password: RULE.required("原密码不能为空"),
        newPassword: [
          { validator: validatePass, trigger: "blur", required: true }
        ],
        passwdCheck: [
          { validator: validatePassCheck, trigger: "blur", required: true }
        ]
      }
    };
  },
  methods: {
    initData() {
      return {
        password: "",
        newPassword: "",
        passwdCheck: ""
      };
    },
    onVisible() {},
    onModalOK() {
      this.submit();
    },
    async submit() {
      const result = await this.$refs.forms.validate();
      if (!result) return;
      this.loading = true;
      await this.$http({
        method: "post",
        url: this.API.UPDATE_PWD,
        data: { ...this.params }
      });
      this.$Message.success("保存成功");
      setTimeout(() => {
        this.$router.push({ name: "Login" });
      }, 1100);
    }
  }
};
</script>

<style>
</style>
